package org.gd.exercise.learnspringbootredis.controller;

import org.gd.exercise.learnspringbootredis.dto.UserDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

/**
* @description: redis的String类型应用场景
* @author name: yushanjiang
* @date         2025/9/12 10:03
* @version      1.0
*/
@RestController
@RequestMapping("/string")
public class StringController {
    @Autowired
    private RedisTemplate redisTemplate;

    /**
    * @description: 场景1：文章阅读量-增加阅读量
    * @param: [articleId]
    * @return java.lang.Long
    * @author name: yushanjiang
    * @date: 2025/9/12 10:32
    */
    @PostMapping("/article/addcount")
    public Long addReadCount(@RequestParam String articleId) {
        String  key = "jys_article:readcount:{" + articleId + "}";
        System.out.println("要修改的key：" + key);
        System.out.println("当前该key的值为：" + redisTemplate.opsForValue().get(key));
        // 自增并返回新值
        return redisTemplate.opsForValue().increment(key);
    }

    /**
    * @description: 场景1：文章阅读量-获取阅读量
    * @param: [articleId]
    * @return java.lang.Object
    * @author name: yushanjiang
    * @date: 2025/9/12 10:32
    */
    @GetMapping("/article/getcount/{articleId}")
    public Object getReadCount(@PathVariable String articleId) {
        String key = "jys_article:readcount:{" + articleId + "}";
        System.out.println("要查询的key：" + key);
        return redisTemplate.opsForValue().get(key);
    }

    /**
    * @description: 场景2：对象缓存-存储对象信息
    * @param: [userId, userInfo]
    * @return java.lang.String
    * @author name: yushanjiang
    * @date: 2025/9/12 11:24
    */
    @PostMapping("/cache/user/{userId}")
    public String cacheUser(@PathVariable String userId,
                            @RequestBody UserDTO userInfo) {
        String key = "jys_user:cache:{" + userId + "}";
        System.out.println("要存储信息的用户ID：" + userId);

        redisTemplate.opsForValue().set(key, userInfo, 2, TimeUnit.HOURS);
        return "缓存成功！userId=" + userId + "，缓存的信息：" + userInfo;
    }

    /**
    * @description: 场景2：对象缓存-获取对象信息
    * @param: [userId]
    * @return java.lang.Object
    * @author name: yushanjiang
    * @date: 2025/9/12 11:25
    */
    @GetMapping("/cache/getuser/{userId}")
    public Object getUser(@PathVariable String userId) {
        String key = "jys_user:cache:{" + userId + "}";
        return redisTemplate.opsForValue().get(key);
    }

}
